package com.example.petshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.petshop.entity.Address;
import com.example.petshop.mapper.AddressMapper;
import com.example.petshop.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> getAddressesByUserId(Long userId) {
        return addressMapper.getAddressesByUserId(userId);
    }

    @Override
    public Address getAddressById(int addressid) {
        return addressMapper.selectByAddressId(addressid);
    }
    @Override
    public Address updateAddress(Address address) {
        addressMapper.updateAddress(address);
        return address;
    }

    @Override
    public Address addAddress(Address address) {
        addressMapper.insertAddress(address);
        return address;
    }

    @Override
    public boolean removeById(int addressid) {
        System.out.println("Impladdressid: " +addressid);
        return addressMapper.deleteById(addressid) > 0;
    }

    @Override
    public Address setAsDefaultAddress(int addressid, Long userId) {
        // 1. 将所有用户的地址设置为非默认（0）
        addressMapper.updateAllAddressesToNonDefault(userId);

        // 2. 设置选中的地址为默认（1）
        Address defaultAddress = (Address) addressMapper.findById(addressid).orElse(null);
        if (defaultAddress != null) {
            addressMapper.updateAddressToDefault(addressid);
            // 由于我们直接更新了数据库，所以需要重新查询地址以获取最新状态
            defaultAddress = (Address) addressMapper.findById(addressid).orElse(null);
            return defaultAddress; // 返回更新后的地址对象
        }
        return null;
    }

    @Override
    public Address getDefaultAddressByUserId(Long userId) {
        return addressMapper.getDefaultAddressByUserId(userId);
    }

}